<template>
  <div>
    <div v-if="isImg">
      <el-image
        v-for="(item,itemIndex) in imgList"
        :key="itemIndex"
        fit="cover"
        :src="item"
        class="column-image"
        :preview-src-list="imgList"
      />
    </div>
    <my-link v-else-if="isLink" :href="text"/>
    <!--    <a :href="text" target="_blank" class="link">{{ text }}</a>-->
    <div v-else-if="showTag">
      <el-tag
        v-if="text"
        :type="tagType"
      >{{
          text
        }}
      </el-tag>
    </div>
    <span v-else-if="column.type === ColumnType.MONEY" class="text">￥ {{ text }}</span>
    <div v-else-if="column.type === ColumnType.RICH_TEXTAREA" class="text" v-html="text"></div>
    <span v-else class="text">{{ text }}</span>
  </div>
</template>

<script>
import ColumnUtil from "@/framework/components/table/ColumnUtil";
import ColumnType from "@/framework/constant/ColumnType";
import TypeDiagnose from "@/framework/infra/type/TypeDiagnose";
import MyLink from "@/framework/components/MyLink";

export default {
  name: "FormColumnRender",
  components: {MyLink},
  props: {
    value: [String, Number],
    column: [Object],
    options: [Array, Object, Function, Promise]
  },
  data() {
    return {
      ColumnType,
      text: '',
      tagType: ''
    }
  },
  computed: {
    showTag() {
      const column = this.column
      return !column.displayProp
        && (column.type === ColumnType.SELECT || column.type === ColumnType.RADIO)
        && column.tagMode !== false
        && (typeof column.options !== 'function' || TypeDiagnose.isEnum(column.options))
        && !(column.options instanceof Promise)
    },
    isLink() {
      return !!this.column.viewAsLink
    },
    isImg() {
      return this.column.type === ColumnType.IMAGE
    },
    imgList() {
      if (this.text) {
        if (Array.isArray(this.text)) {
          return this.text
        }
        return this.text.split(',')
      }
      return []
    }
  },
  watch: {
    async value() {
      this.text = await this.getText()
      this.tagType = await this.getTagType()
    }
  },
  async created() {
    this.text = await this.getText()
    this.tagType = await this.getTagType()
  },
  methods: {
    async getTagType() {
      const value = this.value
      const item = await this.findOptionItem(value)
      let type = item?.type
      if (!type) {
        if (value === 0) {
          type = 'danger'
        } else if (value === 1) {
          type = 'success'
        }
      }
      return type || 'primary'
    },
    async findOptionItem(value) {
      return ColumnUtil.findOptionItem(this.column, value)
    },
    async getText() {
      return ColumnUtil.getText(this.column, this.value)
    }
  }
}
</script>

<style scoped>
.column-image {
  width: 50px;
  height: 50px;
}

.link {
  color: blue;
  text-decoration: underline;
}

.text {
  white-space: pre-line;
}
</style>
